package com.mrent.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import com.mrent.entity.Member;


@Component
public class MemberServiceImpl implements MemberService {
	
	/**
	 * 保存会员.
	 * 
	 * @param member
	 */
	public void saveMember(Member member){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try {
			trans.begin();
			em.persist(member);
		}catch(Exception e){
			System.err.println("异常问题");
			e.printStackTrace();
		}
		finally {
			trans.commit();
		}
	}
	
	/**
	 * 会员列表.
	 * 
	 * @param page
	 * @return
	 */
	public List<Member> listMember(Page page){
		EntityManager em = EMF.getEM();
		Query query = em.createQuery("select from Member");
		page.setTotalCount(query.getResultList().size());
		query.setFirstResult(page.getFirst());
		query.setMaxResults(page.getPageSize());
		List<Member> list = query.getResultList();
		return list;
	}
	
	/**
	 * 获取会员.
	 * 
	 * @param memberId
	 * @return
	 */
	public Member getMember(Long memberId){
		EntityManager em = EMF.getEM();
		Member member = null;
		try{
			member = em.find(Member.class, memberId);
		}catch(Exception e){
			e.printStackTrace();
		}
		return member;
	}
	
	/**
	 * 修改会员.
	 * 
	 * @param member
	 */
	public void modifyMember(Member member){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try {
			trans.begin();
			em.merge(member);
		}catch(Exception e){
			e.printStackTrace();
		}
		finally {	
			trans.commit();
		}
	}
	
	/**
	 * 会员删除.
	 * 
	 * @param memberId
	 */
	public void delMember(Long memberId){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try {
			trans.begin();
			Member member = em.find(Member.class, memberId);
			if(member != null){
				em.remove(member);
			}
		}catch(Exception e){
			System.err.println("异常问题");
			e.printStackTrace();
		}
		finally {
			trans.commit();
		}
		
	}
	
	/**
	 * 根据会员用户名查找.
	 * 
	 * @param memberName
	 * @return
	 */
	public Member findByMemberName(String memberName){
		EntityManager em = EMF.getEM();
		String jpql = "select from Member m where m.memberName =:memberName";
		Member member = null;
		try{
			Query query = em.createQuery(jpql);
			query.setParameter("memberName", memberName);
			List<Member> list = query.getResultList();
			if(list.size() <= 1){
				member = (Member)query.getSingleResult();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return member;
	}

}
